import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { observer } from 'mobx-react';
import { Spin } from 'antd';

import ContentLayout from '@/component/common/ContentLayout';
import houseRecycleStyle from './houseRecycle.scss';

import MModal from '@/component/common/MModal';
import ApiHelper from "../../store/ApiHelper";
import _ from 'lodash';
import format from '@/tool/format';
import helper from '@/tool/helper';

import { recycle_bin_house_list, pull_house_out_of_Recycle_bin, house_his as api_house_his } from '@/constants/ApiTypes';
import { API_URL } from '@/config';

const mConfirm = MModal.confirm;

class HouseDetailModal extends Component {
    static propTypes = {
        visible: PropTypes.bool,
        onClose: PropTypes.func.isRequired,
        houseInfo: PropTypes.object.isRequired
    };
    defaultState = {
        spinning: true,
        detailInfo: {
            owner_info: false,
            rent_his: []
        }
    };
    state = this.defaultState;
    //获取房源历史
    getHouseHis = props => {
        const { houseInfo } = props;
        const data = { house_no: houseInfo.house_no };
        return ApiHelper.requestPost(api_house_his, data);
    };
    async componentWillReceiveProps(nextProps) {
        if (nextProps.visible) {
            this.setState({ ...this.defaultState, spinning: true });
            const result = await this.getHouseHis(nextProps);
            if (result.status) {
                this.setState({ detailInfo: result.info, spinning: false });
            }
        }
    }
    render() {
        const { visible, onClose, houseInfo } = this.props;
        const { owner_info, rent_his } = this.state.detailInfo;
        const rent_list = rent_his.map((val, index) => {
            const label_cls = isNaN(val.calcProfit) ? houseRecycleStyle['list-label-gain'] : (val.calcProfit > 0 ? houseRecycleStyle['list-label-gain'] : houseRecycleStyle['list-label-deficit']);
            const label_text = isNaN(val.calcProfit) ? '利润' : (val.calcProfit > 0 ? '利润' : '亏损');
            const cash_list = val.cashbook.map((item, index2) => {
                return (
                    <div key={index2} className={houseRecycleStyle['list-item-detail-i']}>
                        <span>{item.item_type}</span><span>{format.timeString(item.item_time)}</span><span>{item.balance_type == 1 ? '+' : '-'}{item.item_amount / 100 + '元'}</span>
                    </div>
                );
            });
            return (
                <div key={index} className={houseRecycleStyle['detail-info-item']}>
                    <p className={houseRecycleStyle['list-item-line']}>
                        <span className={houseRecycleStyle['list-label-text']}><b>租客：</b>{val.renter_name}</span>
                        <span className={houseRecycleStyle['list-label-text']}>租金：{val.rent / 100}元</span>
                        <span className={houseRecycleStyle['list-label-text']}>租期：{val.rent_time}</span>
                    </p>
                    <p className={houseRecycleStyle['list-item-line']}>
                        <span className={houseRecycleStyle['list-label-text']}>电话：{val.renter_mobile}</span>
                        <span className={houseRecycleStyle['list-label-text']}>付款：{val.pay_type}</span>
                        <span className={houseRecycleStyle['list-label-text']}>押金：{val.deposit / 100}元</span>
                        <span className={houseRecycleStyle['list-item-oper']}><span className={label_cls}>{label_text}</span><span className={houseRecycleStyle['list-label-text']}>{isNaN(val.calcProfit) ? val.calcProfit : val.calcProfit / 100 + '元'}</span>
                            <a href={`${API_URL}/${val.contract_url}`} target="_blank">查看</a>/<a href={`${API_URL}/${val.contract_pdf_url}`}>下载合同</a></span>
                    </p>
                    <div className={houseRecycleStyle['list-item-line']}>
                        <span className={houseRecycleStyle['list-label-d']}>明细</span>
                        <div className={houseRecycleStyle['list-item-detail']}>
                            {cash_list}
                        </div>
                        <div style={{ clear: 'both' }} />
                    </div>
                </div>
            );
        });
        return (
            <MModal showMask closeMaskOnClick={false} visible={visible} onClose={onClose} width={1000} height={helper.fixHeight(650)} zIndex={101}>
                <Spin tip="loading" spinning={this.state.spinning} delay={150}>
                    <div className={houseRecycleStyle['house-detail-modal']}>
                        {owner_info ?
                            <div className={houseRecycleStyle['detail-modal-head']}>
                                <p>{houseInfo.address_detail}</p>
                                <p>
                                    <span className={houseRecycleStyle['head-label-text']}>房东：{owner_info.owner}</span>
                                    <span className={houseRecycleStyle['head-label-text']}>租金：{!owner_info.rent ? '' : `${owner_info.rent}`.split('-').map(val => val / 100).join('-') + '元'}</span>
                                    <span className={houseRecycleStyle['head-label-text']}>租期：{owner_info.rent_time}</span>
                                </p>
                                <p>
                                    <span className={houseRecycleStyle['head-label-text']}>电话：{owner_info.mobile}</span>
                                    <span className={houseRecycleStyle['head-label-text']}>付款：{owner_info.pay_type}</span>
                                </p>
                            </div> :
                            <div className={houseRecycleStyle['detail-modal-head']}>
                                <p>{houseInfo.address_detail}</p>
                                <p>房东信息暂无</p>
                            </div>}
                        <div className={houseRecycleStyle['detail-info-list']}>
                            {rent_list.length > 0 ? rent_list :
                                <p style={{ textAlign: 'center' }}>合同历史暂无</p>}
                        </div>
                    </div>
                </Spin>
            </MModal>
        );

    }
}

class HouseItem extends Component {
    static propTypes = {
        onClick: PropTypes.func,
        houseData: PropTypes.object.isRequired,
        onChecked: PropTypes.func
    };
    state = {
        checked: false
    };
    onClick = () => {
        if (typeof this.props.onClick == 'function') this.props.onClick();
    };
    checkItem = e => {
        e.stopPropagation();
        this.setState({ checked: !this.state.checked });
        if (this.props.onChecked) this.props.onChecked(this.props.houseData.house_no, !this.state.checked);
    };
    render() {
        const { checked } = this.state;
        const { houseData } = this.props;
        let checkCls = houseRecycleStyle['house-item-check'];
        if (checked) checkCls += ` ${houseRecycleStyle['checked']}`;
        return (
            <div className={houseRecycleStyle['house-item']} onClick={this.onClick}>
                <div className={houseRecycleStyle['house-item-name']} title={`${houseData.community} ${houseData.address_detail}`}>{`${houseData.community} ${houseData.address_detail}`}</div>
                <div className={houseRecycleStyle['house-item-rent']}>
                    <span className={houseRecycleStyle['house-item-rent-amount']}>￥{houseData.rent / 100}元</span><span className={houseRecycleStyle['house-item-renter']}>{houseData.broker_name}</span>
                </div>
                <a className={checkCls} href="javascript:void(0);" onClick={this.checkItem} />
            </div>
        );
    }
}

@observer class HouseRecycle extends Component {
    state = {
        loading: true,
        detailModalVisible: false,
        houseList: [],
        detailModalProps: {
            houseInfo: {}
        },
        checkedList: []
    };
    getRecycleBinHouseList = async () => {
        const result = await ApiHelper.requestPost(recycle_bin_house_list);
        if (!result.status) return;
        this._setState({
            loading: false,
            houseList: result.info
        });
    };
    componentDidMount() {
        this._isMounted = true;
        this.getRecycleBinHouseList();
    }

    //fix 异步setState
    _setState = state => {
        if (this._isMounted) this.setState(state);
    };
    componentWillUnmount() {
        this._isMounted = false;
    }
    closeDetailModal = () => {
        this.setState({ detailModalVisible: false });
    };
    showDetailModal = houseInfo => {
        this.setState({
            detailModalVisible: true,
            detailModalProps: {
                houseInfo
            }
        });
    };
    restoreOnClick = () => {
        const { checkedList } = this.state;
        if (checkedList.length == 0) return MModal.success({ title: '提示', content: '未选择任何房源！' });
        mConfirm({
            title: '确定要还原选中的房源吗？',
            width: 350,
            height: 200,
            okText: '还原',
            showTopClose: false,
            onOk: async () => {
                const data = {
                    house_no: checkedList.join(',')
                };
                const result = await ApiHelper.requestPost(pull_house_out_of_Recycle_bin, data);
                if (result.status) {
                    MModal.success({ title: '操作成功', content: '操作成功', duration: 1.5 });
                    //刷新回收站列表
                    this._setState({ checkedList: [] });
                    this.getRecycleBinHouseList();
                } else {
                    MModal.success({ title: '操作失败', content: result.info });
                }
            },
            onCancel() {}
        });
    };
    onChecked = (house_no, checked) => {
        let checkedList = _.assign(this.state.checkedList);
        const index = _.indexOf(checked, house_no);
        if (index > -1 && checked == false) {
            delete checkedList[index];
        }
        if (index == -1 && checked == true) {
            checkedList.push(house_no);
        }
        this._setState({ checkedList });
    };
    render() {
        const { detailModalVisible, houseList, detailModalProps } = this.state;
        const { closeDetailModal, showDetailModal, restoreOnClick, onChecked } =  this;

        const houseItemList = houseList.map((val, index) => <HouseItem key={val.house_no} houseData={val} onClick={() => showDetailModal(val)} onChecked={onChecked} />);
        return (
            <ContentLayout navTitle="房源-回收站" loading={this.state.loading}>
                <div className={houseRecycleStyle['house-recycle-wrap']}>
                    <div className={houseRecycleStyle['house-list-wrap']}>
                        <div className={houseRecycleStyle['house-recycle-nav']}>
                            <a className={houseRecycleStyle['nav-back-btn']} href="javascript:void(0);" onClick={() => window.history.go(-1)}>返回</a>
                            <span>回收站</span>
                            <a className={houseRecycleStyle['nav-restore-btn']} href="javascript:void(0);" onClick={restoreOnClick}>还原</a>
                        </div>
                        <div className={houseRecycleStyle['house-list']}>
                            {houseItemList}
                        </div>
                    </div>
                    <HouseDetailModal visible={detailModalVisible} onClose={closeDetailModal} {...detailModalProps}/>
                </div>
            </ContentLayout>
        );
    }
}

export default HouseRecycle;